package com.wst.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wst.system.config.exception.GlobalExcetion;
import com.wst.system.interceptor.encrypt.EncryptDecrypt;
import com.wst.system.interceptor.encrypt.EncryptDecryptTime;
import com.wst.system.security.IsAdmin;
import com.wst.system.security.config.JWTConfig;
import com.wst.system.security.config.UserTypeEnum;
import com.wst.system.security.entity.SelfUserEntity;
import com.wst.system.security.entity.SysUserEntity;
import com.wst.system.security.entity.SysUserTokenEntity;
import com.wst.system.security.entity.vo.PasswordVo;
import com.wst.system.security.entity.vo.SysUserEntityAddVo;
import com.wst.system.security.entity.vo.SysUserEntityVo;
import com.wst.system.server.entity.vo.DelManyDataVo;
import com.wst.system.server.entity.vo.PageSearchVo;
import com.wst.system.server.service.SysUserService;
import com.wst.system.server.service.SysUserTokenService;
import com.wst.system.util.CookieUtils;
import com.wst.system.util.ResultUtil;
import com.wst.system.util.SecurityUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/sys_user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @IsAdmin
    @PostMapping("addUser")
    public JSONObject addUser(@Validated @RequestBody SysUserEntityVo vo) throws GlobalExcetion {
        if(!vo.getPassword().equals(vo.getAgainPassword())){
            return ResultUtil.errorInfo("两次输入密码不一致");
        }
        SysUserEntity sysUserEntity=new SysUserEntity();
        BeanUtils.copyProperties(vo, sysUserEntity);
        sysUserService.addUser(sysUserEntity);
        return ResultUtil.successInfo();
    }

    @IsAdmin
    @PostMapping("/page")
    public JSONObject page(@RequestBody PageSearchVo vo){
        IPage<SysUserEntity> sysUserEntityIPage=sysUserService.page(vo.getPageNum(),vo.getPageSize(),vo);
        return ResultUtil.successInfoTable(sysUserEntityIPage.getTotal(),sysUserEntityIPage.getRecords());
    }

    @IsAdmin
    @PostMapping("saveorupdate")
    public JSONObject saveOrUpdate(@Validated @RequestBody SysUserEntityAddVo vo) throws GlobalExcetion {
        SysUserEntity entity=sysUserService.saveOrUpdate(vo);
        return ResultUtil.successInfo(entity);
    }

    @EncryptDecrypt
    @PostMapping("upadtepsd")
    public JSONObject updatePassword(PasswordVo vo) throws GlobalExcetion {
        System.out.println(JSONObject.toJSONString(vo));
        SelfUserEntity selfUser=SecurityUtil.getUserInfo();
        if(!vo.getNewPassword().equals(vo.getAgainPassword())){
            throw new GlobalExcetion(1,"两次密码不一致");
        }
        SysUserEntity sysUserEntity=sysUserService.selectUserByName(selfUser.getUsername());
        if(sysUserEntity!=null){
            if(!new BCryptPasswordEncoder().matches(vo.getOldPassword(), sysUserEntity.getPassword())){
                throw new GlobalExcetion(1,"原密码输入不正确");
            }
            String password=new BCryptPasswordEncoder().encode(vo.getAgainPassword());
            sysUserEntity.setPassword(password);
            sysUserService.updateById(sysUserEntity);
        }
        return ResultUtil.successInfo("密码修改成功");
    }

    @IsAdmin
    @PostMapping("delete")
    public JSONObject delete(@RequestBody DelManyDataVo vo) throws GlobalExcetion {
        sysUserService.deleteIds(vo.getIds());
        return ResultUtil.successInfo("删除成功");
    }

    @EncryptDecryptTime
    @PostMapping("info")
    public JSONObject getUserInfoController(){
        SelfUserEntity selfUser=SecurityUtil.getUserInfo();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("username",selfUser.getUsername());
        jsonObject.put("userId",selfUser.getUserId());
        jsonObject.put("realName",selfUser.getRealname());
        return ResultUtil.successInfo(jsonObject);
    }

    @GetMapping("userinfo")
    public JSONObject getUserInfo(){
        SelfUserEntity selfUser=SecurityUtil.getUserInfo();
        SysUserEntity entity=sysUserService.getById(selfUser.getUserId());
        entity.setPassword(null);
        entity.setStatus(null);
        return ResultUtil.successInfo(entity);
    }

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @GetMapping("/logout")
    public JSONObject logout(HttpServletRequest request){
        SelfUserEntity selfUser=SecurityUtil.getUserInfo();
        String token=request.getHeader(JWTConfig.tokenHeader);
        if(token==null){
            Cookie[] cookies=request.getCookies();
            Cookie cookie= CookieUtils.getCookieByName(cookies,JWTConfig.tokenHeader);
            if(cookie != null) {
                token = cookie.getValue();
            }
        }
        SysUserTokenEntity tokenEntity=sysUserTokenService.getSysUserTokenByToken(token, "user_token");
        if(tokenEntity!=null){
            sysUserTokenService.removeById(tokenEntity.getId());
        }
        List<SysUserTokenEntity> tokenEntityList=sysUserTokenService.getSysUserTokenByUserId(selfUser.getUserId(),"flush_token", tokenEntity.getLogindate());
        if(tokenEntityList!=null && tokenEntityList.size()>0){
            List<Integer> ids=tokenEntityList.stream().map(SysUserTokenEntity::getId).collect(Collectors.toList());
            sysUserTokenService.removeByIds(ids);
        }
        return ResultUtil.successInfo("退出登录成功");
    }


}
